<template>
    <MainLayout>
        <div class="main-container">
            <Supermap ref="supermapRef" />
            <!-- 根据activeNavIndex动态显示面板 -->
            <div class="right-panel" v-if="activeNavIndex > 1">
                <component :is="currentPanelComponent"></component>
            </div>
        </div>
    </MainLayout>
</template>

<script setup>
import { computed, ref, onMounted, watch, provide, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MainLayout from './components/MainLayout.vue'
import Supermap from './supermap/supermap.vue'
import DeviceOverviewPanel from './components/panels/DeviceOverviewPanel.vue'
import VehicleMonitorPanel from './components/panels/VehicleMonitorPanel.vue'
import EmergencyPanel from './components/panels/EmergencyPanel.vue'
import EnergyPanel from './components/panels/EnergyPanel.vue'
import PlanPanel from './components/panels/PlanPanel.vue'

// Supermap组件引用
const supermapRef = ref(null);
const router = useRouter();
const isInitialLoad = ref(true);
const lastNavIndex = ref(-1);

// 提供supermapRef给子组件使用
provide('supermapRef', supermapRef);

// 获取路由参数，用于确定当前显示的面板
const route = useRoute()
const activeNavIndex = computed(() => {
    const navIndex = parseInt(route.query.navIndex)
    return isNaN(navIndex) ? -1 : navIndex
})

// 组件映射表 - 将导航索引映射到对应的组件
const panelComponents = {
    2: DeviceOverviewPanel,
    3: VehicleMonitorPanel,
    4: EmergencyPanel,
    5: EnergyPanel,
    6: PlanPanel,
}

// 根据当前活动的导航索引计算要显示的组件
const currentPanelComponent = computed(() => {
    return panelComponents[activeNavIndex.value] || null
})

// 预加载映射表 - 定义各个导航项需要的预加载操作
const preloadActions = {
    2: async () => { // 设备概况
        console.log('预加载设备概况视图资源');
        if (supermapRef.value) {
            await supermapRef.value.prepareDeviceOverview();
        }
    },
    3: async () => { // 车辆监测
        console.log('预加载车辆监测视图资源');
        // 确保车辆监测页面也加载隧道标记
        if (supermapRef.value && supermapRef.value.loadTunnelMarkers) {
            await supermapRef.value.loadTunnelMarkers();
        }
    },
    4: async () => { // 突发事件
        console.log('预加载突发事件视图资源');
        // 确保突发事件页面也加载隧道标记
        if (supermapRef.value && supermapRef.value.loadTunnelMarkers) {
            await supermapRef.value.loadTunnelMarkers();
        }
    },
    5: async () => { // 能效分析
        console.log('预加载能效分析视图资源');
        // 确保能效分析页面也加载隧道标记
        if (supermapRef.value && supermapRef.value.loadTunnelMarkers) {
            await supermapRef.value.loadTunnelMarkers();
        }
    },
    6: async () => { // 群控预案
        console.log('预加载群控预案视图资源');
        // 确保群控预案页面也加载隧道标记
        if (supermapRef.value && supermapRef.value.loadTunnelMarkers) {
            await supermapRef.value.loadTunnelMarkers();
        }
    }
}

// 预加载指定导航索引的资源
const preloadNavResources = async (navIndex) => {
    if (preloadActions[navIndex]) {
        try {
            await preloadActions[navIndex]();
            return true;
        } catch (error) {
            console.error(`预加载导航索引 ${navIndex} 的资源失败:`, error);
            return false;
        }
    }
    return true;
}

// 监听activeNavIndex变化，确保三维地图在索引2-6时正确显示
watch(activeNavIndex, async (newValue, oldValue) => {
    lastNavIndex.value = oldValue;
    
    if (newValue >= 2 && newValue <= 6) {
        // 通过nextTick确保DOM更新后再操作
        await nextTick();
        
        // 提前预加载资源
        await preloadNavResources(newValue);
        
        console.log(`从导航索引 ${oldValue} 切换到 ${newValue}`);
    } else if (newValue === -1 && oldValue >= 2) {
        console.log('离开三维地图视图');
    }
});

// 进入设备概况时的快速路径
const goToDeviceOverview = async () => {
    // 先预加载资源
    await preloadNavResources(2);
    
    // 然后再跳转路由
    router.push({
        path: '/',
        query: { navIndex: 2 }
    });
}

// 优化路由切换
const optimizeRouteChange = () => {
    const links = document.querySelectorAll('a[href*="navIndex=2"]');
    links.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            goToDeviceOverview();
        });
    });
};

onMounted(async () => {
    // 页面挂载时如果是2-6导航索引，确保三维地图显示
    if (activeNavIndex.value >= 2 && activeNavIndex.value <= 6) {
        console.log('初始化时激活三维地图，索引:', activeNavIndex.value);
        
        // 初始加载时预加载资源
        if (isInitialLoad.value) {
            await nextTick();
            await preloadNavResources(activeNavIndex.value);
            isInitialLoad.value = false;
        }
    } else {
        // 如果没有指定导航索引，默认加载设备概况（索引2）
        console.log('未指定导航索引，默认加载设备概况');
        await nextTick();
        if (supermapRef.value && supermapRef.value.loadTunnelMarkers) {
            await supermapRef.value.loadTunnelMarkers();
        }
    }
    
    // 确保无论何种情况下隧道标记都能加载
    setTimeout(async () => {
        if (supermapRef.value && supermapRef.value.loadTunnelMarkers) {
            await supermapRef.value.loadTunnelMarkers();
        }
    }, 2000);
    
    // 优化路由切换
    setTimeout(optimizeRouteChange, 1000);
})
</script>

<style lang="scss" scoped>
.main-container {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
}

.right-panel {
    position: absolute;
    top: 80px;
    right: 2vw;
    width: 40vw;
    min-width: 340px;
    max-width: 700px;
    pointer-events: auto;
    z-index: 900;
}
</style>